package com.my.kindlesend.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.my.kindlesend.dto.WxLoginRequestDto;
import com.my.kindlesend.entity.UserInfo;
import com.my.kindlesend.result.Result;
import com.my.kindlesend.service.UserInfoService;
import com.my.kindlesend.utils.UserThreadLocal;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/wx")
public class WxUserController {

    private final WxMaService wxMaService;
    private final UserInfoService userInfoService;

    @PostMapping("/login")
    public Result<UserInfo> login(@RequestBody @Valid WxLoginRequestDto wxLoginDto) {
        if (!wxMaService.switchover(wxLoginDto.getAppid())) {
            return Result.error(String.format("未找到对应appid=[%s]的配置，请核实！", wxLoginDto.getAppid()));
        }
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wxLoginDto.getCode());
            log.info("获取用户信息：{}", session);
            UserInfo userInfo = BeanUtil.copyProperties(wxLoginDto, UserInfo.class);
            userInfo.setOpenId(session.getOpenid());
            return Result.success(userInfoService.saveByOpenId(userInfo));
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            return Result.error(e.getMessage());
        } finally {
            WxMaConfigHolder.remove();
        }
    }

    @PostMapping("/updateKindleEmail")
    public Result<UserInfo> updateKindleEmail(@RequestBody @Valid UserInfo userInfo) {
        if (UserThreadLocal.get() == null) {
            return Result.error("用户不存在");
        }
        return Result.success(userInfoService.saveKindleEmail(userInfo.getKindleEmail()));
    }

}
